<template>
	<div>
		<header class="mui-bar mui-bar-nav">
			<a class="iconfont icon-fanhui header_fanhui" @tap="goBack"></a>
			<h1 class="mui-title">意见反馈</h1>
		</header>  
		<div class="mui-content mui-scroll-wrapper">
			<div class="mui-scroll">
        <!-- <crossLine></crossLine> -->
        <form id="feedback_form">
          <!-- 意见反馈 -->
          <div class="title">问题反馈</div>
          <div class="feedback_text">
            <textarea id="text1" placeholder="请填写您的问题反馈" rows="5" name="feedback_text" v-model="resData.problem"></textarea>
            <!-- 图片上传 -->
            <div id="img">
              <!-- <img class="icon" src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1566340971,3030832383&fm=27&gp=0.jpg"/>
              <span class="icon icon-img-01"></span>
              <span class="icon icon-img-01"></span> -->
              <span class="icon icon-img-01" id="icon-img-01" style="position:absolute;z-index:100;font-size:68px" @tap="switchImg"></span>
            </div>
          </div>
          <!-- 建议措施 -->
          <div class="title">建议措施</div>
          <div class="suggest_text">
            <textarea id="textarea"  name="suggest_text" v-model="resData.proposal" placeholder="请填写您的建议措施"></textarea>
          </div>
        </form> 
			</div>
      <button  type="button" class="bt mui-btn mui-btn-primary" @tap="handleFeedback_form">发送</button>
		</div>
	</div>
</template>

<script>
  import mui from 'static/js/mui.js'
  import { Indicator } from 'mint-ui';
  import { mapGetters } from 'vuex'
  import storage from '@/utils/localstorage' 
  import {allvalidated,validatedError}from '@/utils/validator.js'
  import crossLine from '@/components/base/cross-line/cross-line'
  import {uploadBase64, submitFeedback} from "@/api/user"
  import axios from 'axios'
    const IMG_MAX_NUM = 3
    export default {
        components:{crossLine},
        data() {
            return {
              lockerStatus: false,
              complaintsHotline: '',
              feedbackText: '',
              feedback_option:[
                  {
                      name: 'feedback_text',
                      display:"问题反馈必填|问题反馈不能大于50字符|问题反馈小于6字符",
                      rules: 'required|max_length(50)|min_length(6)'
                  },
                  {
                      name: 'suggest_text',
                      display:"建议措施不能大于50字符|建议措施小于6字符",
                      rules: 'max_length(50)|min_length(6)'
                  }
              ],
              question: {
                files: []
              },
              resData:{
                problem: '',
                proposal: '',
                files: []
              },
              index: 0
            }
        },
        props: {},
        watch: {},
        methods:{
          goBack(){
            this.$router.push('/min')
          },
          switchImg(){
            document.getElementById('icon-img-01').style.display='none'
            mui.trigger(document.getElementById('0'),'tap');
            document.getElementById('0').style.display='block'
          },
          handleFeedback_form() {
            let that = this
            //验证所有填写是否都正确 都正确那么跳转下一个目录
            var errors = allvalidated('feedback_form',this.feedback_option)
            if(!errors.length){
              Indicator.open()
              //console.log(this.resData.files)
              this.resData.files =  this.resData.files.join(",");
              submitFeedback(this.resData).then(res=>{
                Indicator.close()
                mui.alert('提交成功', '提示', ['确定'],function() {
                  that.$router.push('/home')
                },'div');     
              })
              ////console.log(this.resData)
              /* this.$store.dispatch('Login',{'login_tel':this.login_mobile,'login_password':login_password}).then(()=>{
                    this.$router.push('/home')
              }) */
            }
          },
          //初始化图片添加器
          init_image_add() {
            let that = this
            let placeholder = document.createElement('span');
            placeholder.setAttribute('class', 'icon_jia icon-jia2 space');
            placeholder.setAttribute('id', this.index);
            this.index++;
            //添加到节点
            document.getElementById('img').appendChild(placeholder);
            placeholder.addEventListener('tap', function(event) {
                //上传图片上限,超过不现实加号
                that.resData.files = that.filterArray(that.question.files)
                if(that.resData.files.length >= IMG_MAX_NUM){
                  //that.resData.files.length)
                  mui.alert('大于上传限制', '提示', ['确定'],function() {},'div');
                  return; 
                }
                var btnArray = [{
                    title: "相册"
                }, {
                    title: "拍照"
                }];

                //actionsheet
                plus.nativeUI.actionSheet({
                    title: "选择图片",
                    cancel: "取消",
                    buttons: btnArray
                }, function(e) {
                    var i = e.index;
                    switch(i) {
                        case 0:
                            break;
                        case 1:
                            plus.gallery.pick(function(e) {
                              //console.log(e)
                              // var url = entry.toURL();
                              var name = e.substr(e.lastIndexOf('/') + 1);

                              //压缩取得缩略图
                              plus.zip.compressImage({
                                  src: e,
                                  dst: '_doc/'+ name,
                                  overwrite: true,
                                  quality:10, 
                                  format: 'jpg',
                                  width:"50%",
                                  height:"50%",
                                  /*  clip: {
                                      top: "25%",
                                      left: "25%",
                                      width: "300px",
                                      height: "300px"
                                  } */
                              }, function(zip) {
                                  Indicator.open()
                                  placeholder.style.backgroundImage = "url('" + zip.target + "')";
                                  placeholder.style.backgroundSize = "100% 100%"
                                  /* if (plus.os.name == 'iOS') {
                                      var relativePath = 'file://compresspic/' + e;
                                  }else{
                                      var relativePath = "compresspic/" + e;  
                                  } */
                                  //检查图片是否已存在  
                                  var relativePath = zip.target
                                  //console.log(relativePath)
                                  //console.log(1)
                                  plus.io.resolveLocalFileSystemURL(relativePath, function(entry) {  
                                    var compress_path = entry.toLocalURL(); // 输入图片的路径,将相对路径转换为绝对路径  
                                    //console.log(2)
                                    if(!placeholder.classList.contains('space')) { //已有图片
                                      //(placeholder)
                                      that.exitUploadHeadImg(placeholder, relativePath)
                                      //that.exFile(that.getChildrenIndex(placeholder), compress_path);
                                    } else { //加号
                                      //console.log(3)
                                      placeholder.classList.remove('space');
                                      placeholder.classList.remove('icon-jia2');
                                      that.createColse(placeholder)
                                      that.uploadHeadImg(compress_path); 
                                      that.init_image_add();
                                    }
                                    // 其他逻辑          
                                  }, function(e) {  
                                    //console.log(e)
                                    mui.alert(e.message, '提示', ['确定'],function() {   
                                        Indicator.close(); 
                                        that.lock = false;
                                    },'div');            
                                });  
                              }, function(zip) {
                                  mui.toast('压缩失败！');
                              });  
                            }, function(e) {
                                //console.log(e);
                            }, {});
                            break;
                        case 2:
                            plus.camera.getCamera().captureImage(function(e) {
                              var name = e.substr(e.lastIndexOf('/') + 1);
                              plus.zip.compressImage({
                                  src: e,
                                  dst: '_doc/'+ name,
                                  overwrite: true,
                                  quality:10, 
                                  format: 'jpg',
                                  width:"50%",
                                  height:"50%",
                                  /*  clip: {
                                      top: "25%",
                                      left: "25%",
                                      width: "300px",
                                      height: "300px"
                                  } */
                              }, function(zip) {
                                  Indicator.open()
                                  placeholder.style.backgroundImage = "url('" + zip.target + "')";
                                  placeholder.style.backgroundSize = "100% 100%"
                                  /* if (plus.os.name == 'iOS') {
                                      var relativePath = 'file://compresspic/' + e;
                                  }else{
                                      var relativePath = "compresspic/" + e;  
                                  } */
                                  //检查图片是否已存在 
                                  var relativePath = zip.target
                                  //console.log(relativePath)
                                  plus.io.resolveLocalFileSystemURL( relativePath, function(entry) {  
                                    var compress_path = entry.toLocalURL(); // 输入图片的路径,将相对路径转换为绝对路径  
                                    if(!placeholder.classList.contains('space')) { //已有图片
                                      //(placeholder)
                                      that.exitUploadHeadImg(placeholder, relativePath)
                                      //that.exFile(that.getChildrenIndex(placeholder), url);
                                    } else { //加号
                                      placeholder.classList.remove('space');
                                      placeholder.classList.remove('icon-jia2');
                                      that.createColse(placeholder)
                                      that.uploadHeadImg(compress_path); 
                                      that.init_image_add();
                                    }
                                    // 其他逻辑          
                                  }, function(e) {  
                                    mui.alert(e.message, '提示', ['确定'],function() {   
                                        Indicator.close(); 
                                        that.lock = false;
                                    },'div');            
                                });  
                              }, function(zip) {
                                  mui.toast('压缩失败！');
                              });
                            }, function(s) {
                                //console.log("error" + s);
                            }, {});
                            break;
                    }
                });

            }, false);
          },
          addFile(url) {
            this.question.files.push(url)
            this.resData.files = this.filterArray(this.question.files)
          },
          removeFile(index){
            delete this.question.files[index]
            this.resData.files = this.filterArray(this.question.files)           
          },
          exFile(index,url){
            this.question.files[index] = url
            this.resData.files = this.filterArray(this.question.files)
          },
          createColse(placeholder){
            //删除图片
            let that = this
            var closeButton = document.createElement('img');
            closeButton.setAttribute('class', 'image-close');
            closeButton.setAttribute('src', 'static/img/cha.png');
            //closeButton.innerHTML = 'X';
            //添加到节点
            placeholder.appendChild(closeButton);
            //小X的点击事件
            closeButton.addEventListener('tap', function(event) {
                that.removeFile(that.getChildrenIndex(placeholder)); //删除实际图片数组元素，先删除数组中的
                placeholder.parentNode.removeChild(placeholder);
               // imageList.removeChild(placeholder); //删除ui，必须后删除，否则节点会找不到
               /*  if(that.files.length == IMG_MAX_NUM - 1){
                    that.init_image_add();
                } */
                event.stopPropagation();
            }, false);
          },
          getChildrenIndex(placeholder){
            return placeholder.id
          },
          //上传图片
          uploadHeadImg(imgPath){//这里的id 会根据判断是手机app  还是webapp  则调用不同的方法
              let that = this
              var images=new Image();
              images.src=imgPath;
              images.onload = function() { 
                  var imgData=that.getBase64Image(images)
                  
                  Indicator.open()
                  axios.post('http://hqg.cnupai.com:8082/common/sysFile/uploadBase64', 
				        	{ "folder":"clientFeedback", 'base64Img': imgData }).then(res=>{
                    that.addFile(res.data);
                    Indicator.close(); 
                  }).catch(error => {
                      Indicator.close();
                      this.lock =false;
                      mui.alert('请求超时请重新提交', '提示', ['确定'],function() {           
                      },'div');
                  })     

              }
          },
          //替换上传图片
          exitUploadHeadImg(placeholder,imgPath){//这里的id 会根据判断是手机app  还是webapp  则调用不同的方法
              let that = this
              var images=new Image();
              images.src=imgPath;
              images.onload = function() { 
                  var imgData=that.getBase64Image(images)
                  
                  Indicator.open()
                  axios.post('http://hqg.cnupai.com:8082/common/sysFile/uploadBase64', 
				        	{ "folder":"clientFeedback", 'base64Img': imgData }).then(res=>{
                    that.addFile(res.data);
                    that.exFile(that.getChildrenIndex(placeholder), res.data);
                    Indicator.close(); 
                  }).catch(error => {
                      Indicator.close();
                      this.lock =false;
                      mui.alert('请求超时请重新提交', '提示', ['确定'],function() {           
                      },'div');
                  })     

              }
          },
          // 压缩图片转成base64
          getBase64Image:function (img){
              var width=img.width;
              var height=img.height;
              var canvas=document.createElement("canvas");
              canvas.width=width;
              canvas.height=height;
              var ctx=canvas.getContext('2d');
              ctx.drawImage(img,0,0,width,height);
              var dataUrl=canvas.toDataURL('image',1);
              return dataUrl.replace('data:image'+':base64,','');
          },
          //过滤空数组
          filterArray(arr){
            let newArr = []
            for(var i = 0; i < arr.length; i++) {
              if(arr[i] == undefined) {
                continue
              }else{
                newArr.push(arr[i])
              }
            }
            return newArr;
          }
        },
        filters: {},
        computed: {
          ...mapGetters([
          ])
        },
        created() {
          this.complaintsHotline = 'tel:'+storage.getLocalstorage('globalConfig').complaintsHotline
          if(storage.getLocalstorage('locker')){
            this.lockerStatus = true
          }else{
            this.lockerStatus = false
          }
          
        },
        mounted() {
          //初始化mui
         	mui.init({
            swipeBack:true //启用右滑关闭功能
          });
          //主界面和侧滑菜单界面均支持区域滚动；
          mui('.mui-scroll-wrapper').scroll();
          //按物理返回键返回至页面首页
          var first = null
          var that = this
          mui.back = function() {
            //首次按键，提示‘再按一次退出应用’
            if (!first) {
              that.$router.push('/min')
            }
          };    
          this.init_image_add()
          document.getElementById('0').style.display='none'
        },
        destroyed() {}
    }
</script>

<style  scoped>
    /* mui.css */
    li{
      list-style-type:none;
    }
    button, textarea {
      font-size: 100%;
      border: 0;
    }
		.mui-bar{
			background-color: #ffffff; 
			-moz-box-shadow:0px 0px 2px rgba(204, 204, 204, 0.5);
			-webkit-box-shadow:0px 0px 2px rgba(204, 204, 204, 0.5); 
			box-shadow:0px 0px 2px rgba(204, 204, 204, 0.5);
		}
    .dataMaintain-neir{
      width:120px;
      height:auto;
      margin:50% auto;
      text-align:center;
      font-size:1.2rem;
      color:#ccc;
      line-height:35px;
    } 
    .mui-table-view-cell{
      background:#fff;
    }
    .mui-switch.mui-active{
      border-color: #ff6a27;
      background-color: #ff6a27;
    }
    .mui-table-view-cell:after {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 15px;
      height: 0px;
      content: '';
      -webkit-transform: scaleY(.5);
      transform: scaleY(.5);
      background-color: #c8c7cc;
    }
    /* 标题 */
    .title{
      background:#f5f5f5;
      height:32px;
      line-height:32px;
      font-size:16px;
      padding-left:12.8px;
      color:#333333;
    }
    .feedback_text{
      width:100%;
      height:11.75rem;
      background: #fff;
    }
    .feedback_text textarea{
      padding:0.5rem;
      width:100%;
      height:6.2rem;
      font-size:1rem;
    }
    .feedback_text #img{
      width:100%;
    }
    .suggest_text{
      width:100%;
      height:9rem;
      background: #fff;
    }
    .suggest_text textarea{
      padding:0.5rem;
      width:100%;
      height:9rem;
      font-size:1rem;
    }
    textarea::-moz-placeholder{   /* Mozilla Firefox 19+ */
      color:#cccccc
    }
    textarea:-moz-placeholder{    /* Mozilla Firefox 4 to 18 */
      color:#cccccc
    }
    textarea:-ms-input-placeholder{  /* Internet Explorer 10-11 */ 
      color:#cccccc
    }
    textarea::-webkit-input-placeholder { /* webkit */
      color:#cccccc
    }
    .bt{
      position: absolute;
      bottom: 5px;
      font-size: 16px;
      left: 5%;
      width: 90%;
      height: 40px;
    }
    /* 上传图片 */
    .icon{
      color:#333333;
      font-size:4.25rem;
      margin:0.8rem;  
      width:4.25rem;
      height:4.25rem;
      margin-top:0rem;
      margin-bottom:0rem;
      float:left;
    }
    /* .icon_jia{
      color:#333333;
      font-size:1.4rem;
      margin:0.8rem;
      padding:0.5rem;  
      width:6.25rem; 
      height:6.25rem;
      margin-top:0rem;
      margin-bottom:0rem;
      border: 1px solid #ddd;
      color:#ddd;
      border-radius: 0.3rem;
      float:left;
    } */
    .icon-jia:before{
      font-size:6.25rem;
    }
    .mui-btn-primary:enabled:active{
      background-color: #ff6a27;
      color: #fff;
      border: 1px solid #ff6a27;
    }
    /* 投诉电话 */
    .complaints{
      float: right;
      width: 6rem;
      height: 44px;
      color:#333333;
      line-height:44px;
      text-align: right;
      font-size:0.8125rem;
    }
    
</style>